//
//  StockAppService.m
//  Stock
//
//  Created by blacksun on 11-6-30.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "StockAppService.h"

@implementation StockAppService 


-(void)signUp{
    UIDevice *device = [UIDevice currentDevice];
    NSString *signUpUrl = [[NSString alloc] initWithFormat:@"%@user/anonymous?d=%@&os=iPhone&sv=%@",kHostName,device.uniqueIdentifier,AppVersionCode];
    NSLog(@"%@",signUpUrl);
    NSURL *url = [[NSURL alloc] initWithString:signUpUrl];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockAppServiceSignUp,kASIHttpRequestUserinfoKey, nil];
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [signUpUrl release];
}
-(void)logout{

    NSString *loginString = [[NSString alloc] initWithFormat:@"%@user/logout?u=%@&sv=%@",kHostName,    [StockContext shareInstance].userId,AppVersionCode];
    NSURL *url = [[NSURL alloc] initWithString:loginString];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockAppServiceLogout,kASIHttpRequestUserinfoKey,nil];
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [loginString release];
}
-(void)loginWithUserId:(NSString *)userId{
    NSString *loginString = [[NSString alloc] initWithFormat:@"%@user/login?u=%@&os=iPhone&sv=%@",kHostName,userId,AppVersionCode];
    NSLog(@"%@",loginString);
    NSURL *url = [[NSURL alloc] initWithString:loginString];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockAppServiceLogin,kASIHttpRequestUserinfoKey,nil];
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [loginString release];
}
-(void)sendPushToken:(NSString *)token{
    NSString *loginString = [[NSString alloc] initWithFormat:@"%@/user/token?t=%@&u=%@",kHostName,token,[StockContext shareInstance].userId];
    NSURL *url = [[NSURL alloc] initWithString:loginString];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [loginString release];
}


#pragma mark -delegate callback
- (void)requestFinished:(ASIHTTPRequest *)request{
    NSDictionary *userinfo = request.userInfo;
    CommonUtil *commonUtil = [CommonUtil shareInstance];
    NSString *action = [userinfo objectForKey:kASIHttpRequestUserinfoKey];
    //NSLog(@"action:%@",action);
    if ([kStockAppServiceLogin isEqualToString:action]) {
        NSString *responseString = [request responseString];
        NSDictionary *json = [responseString JSONValue];
        [StockContext shareInstance].updateTimes = [json objectForKey:@"functions"];
        
        NSArray *sections = [json objectForKey:@"sections"];
        if (!sections || [sections count]==0) {
            [self.delegate requestFinishedwithError:nil andUserinfo:request.userInfo];
            return;
        }
        NSMutableArray *newSections = [NSMutableArray array];
        for (NSDictionary *dict in sections) {
            Section *section = [[Section alloc] init];
            [commonUtil copyMapEntries:dict toObject:section];
            [newSections addObject:section];
            [section release];
        }
        [self.delegate requestFinishedWithResult:newSections andUserinfo:userinfo];
        NSArray *oldSections = [Section allObjects];
        [oldSections makeObjectsPerformSelector:@selector(deleteObject)];
        [super batchAndAsynchronousSaveObjects:newSections];
        
    }else if([kStockAppServiceSignUp isEqualToString:action]){
        NSDictionary *responseDict = [[request responseString] JSONValue];
        if (!responseDict || [responseDict count]==0) {
            [self.delegate requestFinishedwithError:nil andUserinfo:request.userInfo];
            return;
        }
        NSString *userId = [responseDict objectForKey:@"userId"];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        [userDefault setObject:userId forKey:kUserIdInUserDefault];
        [userDefault synchronize];
        //NSLog(@"userid=%@",userId);
        [StockContext shareInstance].userId = userId;
        
        NSArray *sections = [responseDict objectForKey:@"sections"];
        NSMutableArray *newSections = [NSMutableArray array];
        for (NSDictionary *dict in sections) {
            Section *section = [[Section alloc] init];
            [commonUtil copyMapEntries:dict toObject:section];
            [newSections addObject:section];
            [section release];
        }
        [self.delegate requestFinishedWithResult:newSections andUserinfo:userinfo];
        NSArray *oldSections = [Section allObjects];
        [oldSections makeObjectsPerformSelector:@selector(deleteObject)];
        [super batchAndAsynchronousSaveObjects:newSections];
        
        NSArray *stocks = [responseDict objectForKey:@"stocks"];
        NSMutableArray *myStocks = [[NSMutableArray alloc] init];
        for (NSDictionary *dict in stocks) {
            MyStock *myStock = [[MyStock alloc] init];
            [commonUtil copyMapEntries:dict toObject:myStock];
            [myStocks addObject:myStock];
            [myStock release];
        }
        [super batchAndAsynchronousSaveObjects:myStocks];
        [myStocks release];
    }else if([action isEqualToString:kStockAppServiceNewOpinion]){
        NSString *responseString = [request responseString];
        NSDictionary *json = [responseString JSONValue];
        [self.delegate requestFinishedWithResult:[json objectForKey:@"stocks"] andUserinfo:request.userInfo];
    }
}

-(void)queryNewOpinionWithIndex:(NSInteger )index andType:(NSString *)type{
    NSString *loginString = [[NSString alloc] initWithFormat:@"%@/opinion/hotest?type=%@&start=%d",kHostName,type,index*20];
    NSLog(@"%@",loginString);
    NSURL *url = [[NSURL alloc] initWithString:loginString];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockAppServiceNewOpinion,kASIHttpRequestUserinfoKey,nil];
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [loginString release];
    
}


- (void)requestFailed:(ASIHTTPRequest *)request{
    NSError *error = request.error;
    NSLog(@"code=%d,%@",[error code],error);
    [self.delegate requestFinishedwithError:request.error andUserinfo:request.userInfo];
}

@end
